<?php
/*
 $Id$ ecg_wm.php
 ECG, http://www.gtf.16mb.com
 Copyright (c) 2012 Eugene.K
 
 This program is shareware software; all right reserved 
*/


/*
 * The user side of the WebMoney payment module
*/

class osC_Payment_ecg_wm extends osC_Payment
{
	var $_title,
	$_code = 'ecg_wm',
	$_status = false,
	$_sort_order,
	$_order_id;
		
	function osC_Payment_ecg_wm()
	{
		global $osC_Database, $osC_Language, $osC_ShoppingCart;
		
		$this->_title = $osC_Language->get('payment_ecg_wm_title');
		$this->_method_title = $osC_Language->get('payment_ecg_wm_method_title');
		$this->_status = (MODULE_PAYMENT_ECG_WM_STATUS == '1') ? true : false;
		$this->_sort_order = MODULE_PAYMENT_ECG_WM_SORT_ORDER;
			
		if (MODULE_PAYMENT_ECG_WM_LANG=='RUS')
			$this->form_action_url = 'https://merchant.webmoney.ru/lmi/payment.asp';
		
		if (MODULE_PAYMENT_ECG_WM_LANG=='ENGS')
			$this->form_action_url = 'https://merchant.wmtransfer.com/lmi/payment.asp';
		
		if ($this->_status === true)
		{
			if ((int)MODULE_PAYMENT_ECG_WM_ORDER_STATUS_ID > 0)
			{
				$this->order_status = MODULE_PAYMENT_ECG_WM_ORDER_STATUS_ID;
			}
				
			if ((int)MODULE_PAYMENT_ECG_WM_ZONE > 0)
			{
				$check_flag = false;
					
				$Qcheck = $osC_Database->query('select zone_id from :table_zones_to_geo_zones where geo_zone_id = :geo_zone_id and zone_country_id = :zone_country_id order by zone_id');
				$Qcheck->bindTable(':table_zones_to_geo_zones', TABLE_ZONES_TO_GEO_ZONES);
				$Qcheck->bindInt(':geo_zone_id', MODULE_PAYMENT_COD_ZONE);
				$Qcheck->bindInt(':zone_country_id', $osC_ShoppingCart->getBillingAddress('country_id'));
				$Qcheck->execute();
					
				while ($Qcheck->next())
				{
					if ($Qcheck->valueInt('zone_id') < 1)
					{
						$check_flag = true;
						break;
					}elseif ($Qcheck->valueInt('zone_id') == $osC_ShoppingCart->getBillingAddress('zone_id')) 
					{
						$check_flag = true;
						break;
					}
				}
				
				if ($check_flag == false)
				{
					$this->_status = false;
				}
			}
		}
	}
		
	function selection()
	{
		$table='';
		$selection = array('id' => $this->_code,
						   'module' => $this->_method_title,
						   'fields' => array(array('title' => $table,
												   'field' => '')));
		return $selection;
	}
	
	
	function pre_confirmation_check()
	{
		global $osC_OrderTotal, $osC_ShoppingCart, $osC_Currencies, $osC_Language, $osC_ecgclass;
		
		if (MODULE_PAYMENT_ECG_WM_PRICEADD!=0)
		{
			$LabelArray['title_label']=$osC_Language->get('payment_ecg_wm_user_16');
			$LabelArray['code']='ecg_wm_add';
			$osC_ecgclass->addtoprice(MODULE_PAYMENT_ECG_WM_WHATGROW, MODULE_PAYMENT_ECG_WM_PRICEADD, MODULE_PAYMENT_ECG_WM_ADDTYPE, $LabelArray);
		}
	}

	function confirmation() 
	{
		global $osC_Language, $osC_Currencies;
		$ecg_caseForPaymentArray=$this->ecg_selectCase();
		$ecg_caseForPayment=$ecg_caseForPaymentArray['wm_case'];
		$ecgPaymentAmount=$ecg_caseForPaymentArray['wm_amount_text'];
		$ecgPaymentCurs=$osC_Currencies->value($_SESSION['currency']);
		
		$confirmation = array('title' => $this->_method_title,
                            'fields' => array(array('title' => $osC_Language->get('payment_ecg_wm_user_1'),
                                                    'field' => $ecg_caseForPayment),
                                              array('title' => $osC_Language->get('payment_ecg_wm_user_2'),
                                                    'field' => $ecgPaymentAmount)));
		return $confirmation;
	}
	
	function process_button()
	{
		global $osC_Customer, $osC_Language, $osC_MessageStack;
		
		$this->_order_id = osC_Order::insert();
		
		$ecg_caseForPaymentArray=$this->ecg_selectCase();
		$ecg_caseForPayment=$ecg_caseForPaymentArray['wm_case'];
		$ecgPaymentAmount=$ecg_caseForPaymentArray['wm_amount'];
		$ecgPaymentDescription=MODULE_PAYMENT_ECG_WM_DESCRIPTION." ".STORE_NAME." N".$this->_order_id;
		
		$fields=osc_draw_hidden_field('LMI_PAYEE_PURSE', $ecg_caseForPayment);
		$fields.=osc_draw_hidden_field('LMI_PAYMENT_AMOUNT', $ecgPaymentAmount);
		$fields.=osc_draw_hidden_field('LMI_PAYMENT_NO', $this->_order_id);
		$fields.=osc_draw_hidden_field('LMI_PAYMENT_DESC_BASE64', base64_encode($ecgPaymentDescription));
		$fields.=osc_draw_hidden_field('ecg_wmSecret', $osC_Customer->getID());
		
		$SEOString  = MODULE_SERVICES_INSTALLED;
		$SEOSArray = explode(";", $SEOString);
		$SeoSelector=in_array('sefu', $SEOSArray);
		
		if (isset( $_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')
    		$wmProtocol='https';
		else
			$wmProtocol='http';
		
		if ($SeoSelector)
		{
			$fields.=osc_draw_hidden_field("LMI_RESULT_URL", $wmProtocol."://".$_SERVER['HTTP_HOST']."/checkout.php/callback/module,ecg_wm");
			$fields.=osc_draw_hidden_field("LMI_SUCCESS_URL", $wmProtocol."://".$_SERVER['HTTP_HOST']."/checkout.php/process");
			$fields.=osc_draw_hidden_field("LMI_FAIL_URL", $wmProtocol."://".$_SERVER['HTTP_HOST']."/checkout.php/payment");
		}
		
		return $fields;
	}

	function process()
	{
		global $osC_ecgclass;
		$osC_ecgclass->CheckPaymentError();
	}
	
	function callback()
	{
		global $osC_Database, $osC_Language, $osC_MessageStack; extract($_POST);

		if (isset($LMI_PREREQUEST) && $LMI_PREREQUEST==1)
		{
			print $this->_verify($_POST, 1);
		}else
			print ($this->_verify($_POST, 0));
	}
	
	function _verify($DataArray, $PreRequest)
	{
		global $osC_Database, $osC_Language, $osC_Currencies, $osC_MessageStack;
		$ecgResponce=$osC_Language->get('payment_ecg_wm_user_4').": ".$osC_Language->get('payment_ecg_wm_user_5'). ". ".$osC_Language->get('payment_ecg_wm_user_6');
		
		$Qcheck = $osC_Database->query('select orders_id, currency, currency_value from :table_orders where orders_id = :order_id and customers_id = :ecg_wmSecret');
		$Qcheck->bindTable(':table_orders', TABLE_ORDERS);
		$Qcheck->bindInt(':order_id', $DataArray['LMI_PAYMENT_NO']);
		$Qcheck->bindInt(':ecg_wmSecret', $DataArray['ecg_wmSecret']);
		$Qcheck->execute();
		
		if ($Qcheck->numberOfRows()!=1)
		{
			$ecgResponce=$osC_Language->get('payment_ecg_wm_user_3')." ".$DataArray['LMI_PAYMENT_NO'];
			$desc=$ecgResponce;
			$trans_code=2;
			$trans_status=2;
		}
		else
		{
			$WmValueArray=$this->_DetectCase($Qcheck->value('currency'), $Qcheck->value('currency_value'));
			$Qcheck1 = $osC_Database->query('select value from :table_orders_total where orders_id = :order_id and class = :class');
			$Qcheck1->bindTable(':table_orders_total', TABLE_ORDERS_TOTAL);
			$Qcheck1->bindInt(':order_id', $DataArray['LMI_PAYMENT_NO']);
			$Qcheck1->bindValue(':class', 'total');
			$Qcheck1->execute();
			
			$AmountCheckWM=$osC_Currencies->formatRaw($DataArray['LMI_PAYMENT_AMOUNT']);
			$AmountCheckOrder=$osC_Currencies->formatRaw($Qcheck1->valueDecimal('value'), $WmValueArray['wm_code']);
			
			if (MODULE_PAYMENT_ECG_WM_MODE==1)
				$wmMode='0';
			elseif(MODULE_PAYMENT_ECG_WM_MODE==-1)
				$wmMode='1';
			
			if ($WmValueArray['wm_case']===$DataArray['LMI_PAYEE_PURSE'] && $AmountCheckOrder===$AmountCheckWM && $DataArray['LMI_MODE']===$wmMode)
				$ecgResponce="YES";
			
			if ($ecgResponce==="YES")
			{
				$desc="\r\n".($osC_Language->get('payment_ecg_wm_user_7'))." ".$DataArray['LMI_PAYER_WM']." (".$DataArray['LMI_PAYER_PURSE'].")";
				
				if (isset($DataArray['LMI_PAYMER_NUMBER']) && $DataArray['LMI_PAYMER_NUMBER']!='')
					$desc.="\r\n".$osC_Language->get('payment_ecg_wm_user_8')." ".$DataArray['LMI_PAYMER_NUMBER'];
				
				if (isset($DataArray['LMI_EURONOTE_NUMBER']) && $DataArray['LMI_EURONOTE_NUMBER']!='')
					$desc.="\r\n".$osC_Language->get('payment_ecg_wm_user_9')." ".$DataArray['LMI_EURONOTE_NUMBER'];
				
				if (isset($DataArray['LMI_WMCHECK_NUMBER']) && $DataArray['LMI_WMCHECK_NUMBER']!='')
					$desc.="\r\n".$osC_Language->get('payment_ecg_wm_user_10')." ".$DataArray['LMI_WMCHECK_NUMBER'];
				
				if (isset($DataArray['LMI_TELEPAT_PHONENUMBER']) && $DataArray['LMI_TELEPAT_PHONENUMBER']!='')
					$desc.="\r\n".$osC_Language->get('payment_ecg_wm_user_11')." ".$DataArray['LMI_TELEPAT_PHONENUMBER'];
				
				if (isset($DataArray['LMI_TELEPAT_ORDERID']) && $DataArray['LMI_TELEPAT_ORDERID']!='')
					$desc.="\r\n".$osC_Language->get('payment_ecg_wm_user_12')." ".$DataArray['LMI_TELEPAT_ORDERID'];
				
				$trans_status=1;
				if ($PreRequest==1)
				{
					$trans_code=1; 
				}elseif($PreRequest==0)
				{
					$CalculatedHash=$WmValueArray['wm_case'].$AmountCheckOrder.$Qcheck->value('orders_id').$wmMode.$DataArray['LMI_SYS_INVS_NO'].$DataArray['LMI_SYS_TRANS_NO'].$DataArray['LMI_SYS_TRANS_DATE'].MODULE_PAYMENT_ECG_WM_SECRET.$DataArray['LMI_PAYER_PURSE'].$DataArray['LMI_PAYER_WM'];
					$ecg_oderIdForTable=$Qcheck->value('orders_id');
					$CalculatedHash=md5($CalculatedHash);
					$CalculatedHash=strtoupper($CalculatedHash);
					
					if ($CalculatedHash===$DataArray['LMI_HASH'])
					{
						$trans_code=3;
						$trans_status=1;
						
						osC_Order::process($Qcheck->valueInt('orders_id'), $this->order_status);
					}else
					{
						$trans_code=3;
						$trans_status=2;
						$desc=$osC_Language->get('payment_ecg_wm_user_4').": ".$osC_Language->get('payment_ecg_wm_user_5'). ". ".$osC_Language->get('payment_ecg_wm_user_17');
						$osC_Database->simpleQuery("insert into " . DB_TABLE_PREFIX . "order_payment_ecg (ecg_order_id, ecg_payment_status_id, ecg_descr) values ('$ecg_oderIdForTable', '1', '$desc')");
					}
					
					if (isset($DataArray['LMI_SYS_INVS_NO']) && $DataArray['LMI_SYS_INVS_NO']!='')
						$desc.="\r\n".$osC_Language->get('payment_ecg_wm_user_13')." ".$DataArray['LMI_SYS_INVS_NO'];
						
					if (isset($DataArray['LMI_SYS_TRANS_NO']) && $DataArray['LMI_SYS_TRANS_NO']!='')
						$desc.="\r\n".$osC_Language->get('payment_ecg_wm_user_14')." ".$DataArray['LMI_SYS_TRANS_NO'];
						
					if (isset($DataArray['LMI_SYS_TRANS_DATE']) && $DataArray['LMI_SYS_TRANS_DATE']!='')
						$desc.="\r\n".$osC_Language->get('payment_ecg_wm_user_15')." ".$DataArray['LMI_SYS_TRANS_DATE'];
				}
			}else
			{
				$desc=$ecgResponce;
				$trans_code=2;
				$trans_status=2;
			}
		}
		
		$Qtransaction = $osC_Database->query('insert into :table_orders_transactions_history (orders_id, transaction_code, transaction_return_value, transaction_return_status, date_added) values (:orders_id, :transaction_code, :transaction_return_value, :transaction_return_status, now())');
		$Qtransaction->bindTable(':table_orders_transactions_history', TABLE_ORDERS_TRANSACTIONS_HISTORY);
		$Qtransaction->bindInt(':orders_id', $Qcheck->value('orders_id'));
		$Qtransaction->bindInt(':transaction_code', $trans_code);
		$Qtransaction->bindValue(':transaction_return_value', $desc);
		$Qtransaction->bindInt(':transaction_return_status', $trans_status);
		$Qtransaction->execute();
		
		return $ecgResponce;
	}
	
	function _DetectCase($WmCurrency, $WmCurrencyValue)
	{
		global $osC_Currencies; $responceCaseArray='';
		
		if (MODULE_PAYMENT_ECG_WM_CURENCY_USE==1)
		{
			$responceCaseArray=$this->_choose(DEFAULT_CURRENCY);
			if ($responceCaseArray['wm_case']=='')
				$responceCaseArray=$this->_choose(MODULE_PAYMENT_ECG_WM_ALT_CURRENCY);
		}else
		{
			$responceCaseArray=$this->_choose($WmCurrency);
			if ($responceCaseArray['wm_case']=='')
				$responceCaseArray=$this->_choose(MODULE_PAYMENT_ECG_WM_ALT_CURRENCY);
		}
		return $responceCaseArray;
	}
	
	function _choose($currency)
	{
		$case1=array();
		$case1['wm_case']=''; $case1['wm_code']='';
		$caseArray=array(array('id'=>'USD', 'text'=>'WMZ', 'ecg_case'=>MODULE_PAYMENT_ECG_WM_WMZ),
					array('id'=>'EUR', 'text'=>'WME', 'ecg_case'=>MODULE_PAYMENT_ECG_WM_WME),
					array('id'=>'RUB', 'text'=>'WMR', 'ecg_case'=>MODULE_PAYMENT_ECG_WM_WMR),
					array('id'=>'UAH', 'text'=>'WMU', 'ecg_case'=>MODULE_PAYMENT_ECG_WM_WMU),
					array('id'=>'BYR', 'text'=>'WMB', 'ecg_case'=>MODULE_PAYMENT_ECG_WM_WMB),
					array('id'=>'UZS', 'text'=>'WMY', 'ecg_case'=>MODULE_PAYMENT_ECG_WM_WMY));
		foreach ($caseArray as $key=>$value)
		{
			if ($value['id']==$currency)
			{
				$case1['wm_case']=$value['ecg_case'];
				$case1['wm_code']=$value['id'];
				break;
			}
		}
		return $case1;
	}
	

	function ecg_selectCase()
	{
		$SelectCase='';
		if (MODULE_PAYMENT_ECG_WM_CURENCY_USE==1)
			$SelectCase=DEFAULT_CURRENCY;
		else
			$SelectCase=$_SESSION['currency'];
		
		$SelectedCase= $this->ecg_checkCase($SelectCase);
		if (!$SelectedCase)
			$SelectedCase=$this->ecg_checkCase(MODULE_PAYMENT_ECG_WM_ALT_CURRENCY);
		
		return $SelectedCase;
	}
	
	function ecg_checkCase($SelectedCurrency)
	{
		global $osC_Currencies;
		$caseArray=array(array('id'=>'USD', 'text'=>'WMZ', 'ecg_case'=>MODULE_PAYMENT_ECG_WM_WMZ),
						array('id'=>'EUR', 'text'=>'WME', 'ecg_case'=>MODULE_PAYMENT_ECG_WM_WME),
						array('id'=>'RUB', 'text'=>'WMR', 'ecg_case'=>MODULE_PAYMENT_ECG_WM_WMR),
						array('id'=>'UAH', 'text'=>'WMU', 'ecg_case'=>MODULE_PAYMENT_ECG_WM_WMU),
						array('id'=>'BYR', 'text'=>'WMB', 'ecg_case'=>MODULE_PAYMENT_ECG_WM_WMB),
						array('id'=>'UZS', 'text'=>'WMY', 'ecg_case'=>MODULE_PAYMENT_ECG_WM_WMY));
		
		$total_index=count($_SESSION['osC_ShoppingCart_data']['order_totals']);
		$ecgPaymentAmount=$_SESSION['osC_ShoppingCart_data']['order_totals'][($total_index-1)]['value'];
		
		$SelectedCase=array();
		foreach ($caseArray as $key => $value)
		{
			if ($value['id']==$SelectedCurrency)
			{
				$SelectedCase['ecg_currency']=$value['id'];
				$SelectedCase['wm_case']=$value['ecg_case'];
				
				if (empty($SelectedCase['wm_case']) || $SelectedCase['wm_case']=='')
				{
					$temp=$this->ecg_checkCase(MODULE_PAYMENT_ECG_WM_ALT_CURRENCY);
					$SelectedCase['wm_case']=$temp['wm_case'];
					$SelectedCase['wm_amount']=$osC_Currencies->formatRaw($ecgPaymentAmount, MODULE_PAYMENT_ECG_WM_ALT_CURRENCY);
					$SelectedCase['wm_amount_text']=$osC_Currencies->format($ecgPaymentAmount, MODULE_PAYMENT_ECG_WM_ALT_CURRENCY);
					break;
				}
				
				if ($SelectedCurrency==DEFAULT_CURRENCY)
				{
					$SelectedCase['wm_amount']=$ecgPaymentAmount;
					$SelectedCase['wm_amount_text']=$osC_Currencies->format($ecgPaymentAmount, DEFAULT_CURRENCY);
				}
				else
				{
					$SelectedCase['wm_amount']=$osC_Currencies->formatRaw($ecgPaymentAmount, $value['id']);
					$SelectedCase['wm_amount_text']=$osC_Currencies->format($ecgPaymentAmount, $value['id']);
				}
				break;
			}else
				$SelectedCase=false;
		}
		return $SelectedCase;
	}
}
?>

